/**
 * 文件：activity_Task_Detailed_List.java
 * 包名：com.ronri.ams.task;   --- 正式发布时需要修正
 * 说明：任务信息列表
 * 作者：MS During
 * 日期：2017/5/6
 * 历史：
 */
package com.ronri.ams.task;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.application.InitApplication;
import com.ronri.ams.SystemEnvironmental;
import com.ronri.ams.bean.sample_info;
import com.ronri.ams.bean.taskListBean;
import com.ronri.ams.bean.tb_sampleinfo;
import com.ronri.ams.sample.abstract_activity;
import com.ronri.ams.sample.activity_form_sample;
import com.ronri.common.DateUtil;
import com.ronri.common.UrlEncode;
import com.ronri.common.WaitDialog;
import com.ronri.db.RemoteDataService;

import org.loader.opendroid.db.OpenDroid;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.cz.nongyetongv5.application.InitApplication.LoginInfo;
import static com.cz.nongyetongv5.application.InitApplication.gSampleInfo;
import static com.ronri.ams.SystemEnvironmental.Sample_DELETE;


public class activity_Task_Detailed_List extends abstract_activity {

    // 列表数据
    private List<Map<String, Object>> mItems = new ArrayList<Map<String, Object>>();

    // 任务信息
    private taskListBean mTaskListBean = null;

    // 返回按钮
    private RelativeLayout btnBack = null;

    // 列表视图
    private ListView mListView = null;

    private Context mContext = null;

    private int mProject_id = -1;
    private int mNature = 1;
    private String mDeptName = "";
    private String mEndDate = "";
    private int mType = 0;
    private int mCurrentPoint = -1;

    private TextView mAlready = null;
    private TextView mWait = null;
    private SimpleAdapterWithEvent mAdapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.task_detailed_list);
        Log.i("aaa","activity_Task_Detailed_List");
        btnBack = (RelativeLayout) findViewById(R.id.btnBack);

        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        // CreateDemoData();

        TextView textView = (TextView) findViewById(R.id.title_text_tv);
        textView.setText("任务列表");

        mAlready = (TextView)findViewById(R.id.bt_task_already);
        mWait = (TextView)findViewById(R.id.bt_task_wait);

        Bundle bundle = getIntent().getExtras();

        if (bundle != null) {
            mType = bundle.getInt("type");
            mProject_id = bundle.getInt("project_id");
            mNature = bundle.getInt("nature");
            mDeptName = bundle.getString("dept_name");
            mEndDate = bundle.getString("end_date");
        }

        mContext = this;

        mListView = (ListView) findViewById(R.id.listTaskDetail);

        getRemoteData();
    }


    /***
     * 添加后保存
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == SystemEnvironmental.Sample_MAIN) {
                if (data != null) {
                    String szJson = JSON.toJSONString(gSampleInfo);
                    tb_sampleinfo sinfo = new tb_sampleinfo();
                    sinfo.setPid(gSampleInfo.getProject_id());
                    sinfo.setTid(gSampleInfo.getTask_id());
                    sinfo.setDtime(DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
                    sinfo.setEntname(gSampleInfo.getInspectd_name());
                    sinfo.setStatus("0");
                    sinfo.setHumen(gSampleInfo.getSample_user());
                    sinfo.setTname(gSampleInfo.getTask_name());
                    sinfo.setPname(gSampleInfo.getProject_name());
                    sinfo.setSamplename(gSampleInfo.GetSamplebreed());
                    sinfo.setJson(szJson);

                    sinfo.save();

                    if (mCurrentPoint != -1)
                    {
                        int ii = mTaskListBean.getData().getRows().get(mCurrentPoint).GetWait();
                        mTaskListBean.getData().getRows().get(mCurrentPoint).SetWait(ii + 1);
                        if(mAdapter != null) {
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                }
            }

            // 删除
            if(requestCode == Sample_DELETE){
                if (data.getExtras().containsKey("delete")){
                    if (mCurrentPoint != -1)
                    {
                        int ii = mTaskListBean.getData().getRows().get(mCurrentPoint).GetWait();
                        mTaskListBean.getData().getRows().get(mCurrentPoint).SetWait(ii - 1);
                        if(mAdapter != null) {
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                }
            }
        }
    }

    // 刷新
    private void Refresh(){

    }

    /****
     * 获取远程数据
     */
    public void getRemoteData() {

        RemoteDataService remoteDataService = new RemoteDataService();

        // 获取远程地址
        String szRemoteAddress = InitApplication.SystemConfig.getBase().RemoteAddress(
                InitApplication.SystemConfig.getModule().getTlist().getAddress());

        Map<String, Object> mParam = new HashMap<String, Object>();

        try {
            mParam.put("addFrom", 1);
            mParam.put("addMark", "android");
            mParam.put("page", 1);
            mParam.put("pageSize", 50);
            mParam.put("user_id", LoginInfo.getData().getUser_id());
            mParam.put("detector_id", LoginInfo.getData().getDetectorid());
            mParam.put("project_id", mProject_id);
            mParam.put("nature", mNature);
            mParam.put("dept_name", mDeptName);
            mParam.put("end_date", mEndDate);

        } catch (Exception ex) {

        }

        // 获取远程数据
        remoteDataService.getRemoteData(szRemoteAddress,
                UrlEncode.getUrlParamsByMap(mParam, false),
                InitApplication.SystemConfig.getModule().getTdetail().getMethod(),
                new RemoteDataService.OnRemoteDataEvent() {
                    // 返回结果
                    @Override
                    public void OnResultEvent(String szString) {
                        if (szString.isEmpty())
                            return;

                        try {
                            mTaskListBean = JSON.parseObject(szString, taskListBean.class);

                            if (mTaskListBean.isSuccess()) {
                                if (mListView != null) {
                                    // 循环添加数据
                                    for (taskListBean.DataBean.RowsBean iTem : mTaskListBean.getData().getRows()) {
                                        Map<String, Object> ii = new HashMap<String, Object>();

                                        iTem.SetWait(bussiness.getWaitUpload(mProject_id, iTem.getTask_id()));
                                        ii.put("title", iTem.getTask_name());
                                        ii.put("date", iTem.getEnd_date());
                                        ii.put("deptname", iTem.getDept_name());
                                        ii.put("nature", iTem.getSection_name());
                                        ii.put("regionname", iTem.getRegion_name());
                                        ii.put("samplename", iTem.getBreed_name());

                                        mItems.add(ii);
                                    }

                                    // 获取List视图
                                    mListView = (ListView) findViewById(R.id.listTaskDetail);

                                    mAdapter = new SimpleAdapterWithEvent(
                                            mContext,
                                            R.layout.v_task_detailed_list_item,
                                            mTaskListBean,
                                            new int[]{R.id.bt_do_sample, R.id.bt_task_already, R.id.bt_task_wait},
                                            new OnControlClickEvent() {
                                                @Override
                                                public void OnClick(View view, int Target) {

                                                    // 获取位置，便于读取数据
                                                    int postion = (Integer) view.getTag();
                                                    mCurrentPoint = postion;
                                                    switch (Target) {
                                                        case R.id.bt_do_sample: {
                                                            List<taskListBean.DataBean.RowsBean> items = mTaskListBean.getData().getRows();

                                                            Intent intent = new Intent(getApplicationContext(), activity_form_sample.class);
                                                            Bundle bundle = new Bundle();

                                                            String[] szSectionName = items.get(postion).getSection_name().split(",");
                                                            String[] szSection = items.get(postion).getSection().split(",");
                                                            String szSplit = "";
                                                            String szSec = "";
                                                            for (int i = 0; i < szSection.length; i++) {
                                                                szSec += szSplit + "{\"section_name\":\"" + szSectionName[i] + "\",\"section_id\":" + szSection[i] + "}";
                                                                szSplit = ",";
                                                            }

                                                            szSec = "[" + szSec + "]";

                                                            gSampleInfo = new sample_info();
                                                            // 设置样品类型
                                                            gSampleInfo.setNature(mNature);
                                                            gSampleInfo.szDefaultRegionCode = items.get(postion).getRegion_code();
                                                            gSampleInfo.setArea_name(items.get(postion).getRegion_name());
                                                            gSampleInfo.setSample_area(items.get(postion).getRegion_code());
                                                            gSampleInfo.setDetector_id(LoginInfo.getData().getDetectorid());
                                                            gSampleInfo.setDetector_name(LoginInfo.getData().getDetector_name());
                                                            gSampleInfo.setCreate_user(LoginInfo.getData().getUser_id());
                                                            gSampleInfo.setProject_id(items.get(postion).getProject_id());
                                                            gSampleInfo.setSample_attach(new ArrayList<sample_info.SampleAttachBean>());
                                                            gSampleInfo.setSample_sign(new ArrayList<sample_info.SampleSignBean>());
                                                            gSampleInfo.setTaskBreed(items.get(postion).getBreed());
                                                            gSampleInfo.setSample_user(String.valueOf(LoginInfo.getData().getUser_id()));
                                                            gSampleInfo.setUser_name(LoginInfo.getData().getName());
                                                            gSampleInfo.setTask_id(items.get(postion).getTask_id());

                                                            String sid[] = items.get(postion).getSection().split(",");
                                                            String sname[] = items.get(postion).getSection_name().split(",");

                                                            if (sid.length > 0)
                                                                gSampleInfo.setSection(sid[0]);
                                                            if (sname.length > 0)
                                                                gSampleInfo.setSection_name(sname[0]);

                                                            gSampleInfo.setTask_name(items.get(postion).getTask_name());
                                                            gSampleInfo.setSample_date(DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"));

                                                            bundle.putInt("id", 1);
                                                            bundle.putString("dict", szSec);
                                                            intent.putExtras(bundle);
                                                            startActivityForResult(intent, SystemEnvironmental.Sample_MAIN);
                                                        }
                                                        break;
                                                        case R.id.bt_task_already: {
                                                            List<taskListBean.DataBean.RowsBean> items = mTaskListBean.getData().getRows();
                                                            List<tb_sampleinfo> result = OpenDroid.query.where("tid = ?",
                                                                    String.valueOf(items.get(postion).getTask_id()))
                                                                    .find(tb_sampleinfo.class);

                                                            Intent intent = new Intent(getApplicationContext(), activity_sample_info_already_upload.class);
                                                            Bundle bundle = new Bundle();

                                                            bundle.putInt("pid", items.get(postion).getProject_id());
                                                            bundle.putInt("tid", items.get(postion).getTask_id());

                                                            bundle.putString("data", JSON.toJSONString(result));
                                                            bundle.putString("title", items.get(postion).getTask_name());
                                                            intent.putExtras(bundle);

                                                            startActivity(intent);
                                                        }
                                                        break;
                                                        case R.id.bt_task_wait: {
                                                            List<taskListBean.DataBean.RowsBean> items = mTaskListBean.getData().getRows();
                                                            List<tb_sampleinfo> result = OpenDroid.query.where("tid = ? and status = 0",
                                                                    String.valueOf(items.get(postion).getTask_id()))
                                                                    .find(tb_sampleinfo.class);

                                                            Intent intent = new Intent(getApplicationContext(), activity_sample_info_wait_upload.class);
                                                            Bundle bundle = new Bundle();

                                                            bundle.putString("data", JSON.toJSONString(result));
                                                            bundle.putString("title", items.get(postion).getTask_name());
                                                            intent.putExtras(bundle);
                                                            startActivityForResult(intent, Sample_DELETE);
                                                        }
                                                        break;
                                                    }
                                                }
                                            }
                                    );


                                    mListView.setAdapter(mAdapter);

                                    mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                            // 判断范围
                                            if (i <= mTaskListBean.getData().getRows().size()) {

                                                taskListBean.DataBean.RowsBean iTem = mTaskListBean.getData().getRows().get(i);

                                                Intent intent = new Intent(getApplicationContext(), activity_task_detail.class);
                                                Bundle bundle = new Bundle();
                                                bundle.putInt("project_id", mProject_id);
                                                bundle.putInt("task_id", iTem.getTask_id());
                                                bundle.putInt("nature", mNature);

                                                intent.putExtras(bundle);

                                                startActivity(intent);
                                            }
                                        }
                                    });
                                }
                            } else {
                                // 提示错误信息
                            }
                        } catch (Exception ex) {

                        }
                    }

                    // 状态控制，是否显示加载过程
                    @Override
                    public void OnRuningState(int nStatus) {
                        if(nStatus == SystemEnvironmental.StartGetDataFromServer){
                            WaitDialog.ShowDialog(mContext, "请稍后...");
                        }else{
                            WaitDialog.HideDialog();
                        }
                    }

                    @Override
                    public String OnGetCustomParam() {
                        return null;
                    }
                }
        );
    }
}
